﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MergeInfo.Modal.DAO;
using MergeInfo.Modal.Entity;
using MergeInfo.Modal.Exception;
using MergeInfo.Modal.Interface.IBLL;
using MergeInfo.Modal.Interface.IDAO;

namespace MergeInfo.Modal.BLL
{
    public class ShopBll : IShopBll
    {
        private readonly IShopDao _shopDao;

        public ShopBll()
        {
            _shopDao = new ShopDao();
        }

        public ShopEntity New(ShopEntity shopEntity)
        {
            IList<ShopEntity> shopEntities = Select(shopEntity.Name);
            if (shopEntities.Count > 0)
                throw new ShopException("商家名重复：" + shopEntity.Name);
            shopEntity.Id = Guid.NewGuid();
            shopEntity.CreateTime = DateTime.Now;
            shopEntity.Status = new DataDictionaryEntity { Id = 100001001 };
            _shopDao.Create(shopEntity);
            return shopEntity;
        }

        public ShopEntity Save(ShopEntity shopEntity)
        {
            IList<ShopEntity> shopEntities = Select(shopEntity.Name);
            if (shopEntities.Count > 1)
                throw new ShopException("数据异常：商家名称重复[" + shopEntity.Name + "]");
            if (shopEntities.Count == 1)
            {
                shopEntity.Id = shopEntities[0].Id;
                return Update(shopEntity);
            }
            return New(shopEntity);
        }

        public ShopEntity Update(ShopEntity shopEntity)
        {
            ShopEntity old = GetInfo(shopEntity.Id);
            if (old == null)
                throw new ShopException("未找到商家：Id" + shopEntity.Id);
            old.Address = shopEntity.Address;
            old.District = shopEntity.District;
            old.EMail = shopEntity.EMail;
            old.Fax = shopEntity.Fax;
            old.Name = shopEntity.Name;
            old.Road = shopEntity.Road;
            old.Telephone = shopEntity.Telephone;
            old.UpdateTime = DateTime.Now;
            old.UpdateUser = shopEntity.UpdateUser;
            _shopDao.Update(old);
            return old;
        }

        public IList<ShopEntity> Select(string name)
        {
            return _shopDao.Select(name);
        }


        public ShopEntity GetInfo(Guid id)
        {
            IList<ShopEntity> shopEntities = _shopDao.Select(id);
            if (shopEntities.Count > 1)
                throw new ShopException("数据异常：商家重复");
            if (shopEntities.Count == 1)
                return shopEntities[0];
            return null;
        }
    }
}
